package com.mapler.neteller.service;

import com.mapler.service.MailRunner;
import com.mapler.utility.HttpHelper;
import com.mapler.utility.IConstant;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Properties;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author Mithun
 */
public class NetellerHotMailHelper {

    private static Logger log = Logger.getLogger(MailRunner.class);

    public static void readHotmail(String username, String uPassword, String id, String email, String password) {
        try {
            /* Set the mail properties */
            if (email == null || email.isEmpty()) {
                log.debug("run:: Email address is empty. ");
                return;
            }

            if (password == null || password.isEmpty()) {
                log.debug("run:: Email password is empty. ");
                return;
            }

            Properties props = System.getProperties();
            props.setProperty("mail.store.protocol", "pop3s");

            /* Create the session and get the store for read the mail. */
            Session session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("pop3s");
            store.connect("pop3.live.com", email, password);

            /* Mention the folder name which you want to read. */
            Folder inbox = store.getFolder("Inbox");
            inbox.open(Folder.READ_WRITE);
            /* Get the messages which is unread in the Inbox */
            Message messages[] = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
            /* Use a suitable FetchProfile */
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.CONTENT_INFO);
            inbox.fetch(messages, fp);
            try {
                for (int i = 0; i < messages.length; i++) {
                    Message message = messages[i];
                    parseMessage(message, username, uPassword, id);
                }
                inbox.setFlags(messages, new Flags(Flags.Flag.SEEN), true);
                inbox.close(true);
                store.close();
            } catch (Throwable ex) {
                log.debug("readMail :: Exception arise at the time of read mail " + ex);
                ex.printStackTrace();
            }
        } catch (NoSuchProviderException ex) {
            log.debug("readMail :: Error on NoSuchProviderException " + ex);
            ex.printStackTrace();
        } catch (MessagingException ex) {
            log.debug("readMail :: Error on MessagingException " + ex);
            ex.printStackTrace();
        } catch (Throwable ex) {
            log.debug("readMail :: Error on MessagingException " + ex);
            ex.printStackTrace();
        }
    }

    private static void parseMessage(Message message, String username, String uPassword, String id) throws Exception {
        try {
            String sub = message.getSubject();
            if (!sub.contains("referred you to NETELLER")) {
                return;
            }
            String contentType = message.getContentType();
            System.out.println("Content Type : " + contentType);
            boolean found = false;
            try {
                if (message.getContent() instanceof Multipart) {
                    Multipart mp = (Multipart) message.getContent();
                    int count = mp.getCount();
                    for (int j = 0; j < count; j++) {
                        String s = mp.getBodyPart(j).getContent().toString();
                        String lines[] = s.split("\\r?\\n");
                        for (int k = 0; k < lines.length; k++) {
                            if (lines[k].contains("https://member.neteller.com/member/signUp?")) {
                                String html = lines[k];
                                org.jsoup.nodes.Document doc = Jsoup.parse(html);
                                Elements links = doc.select("a[href]");
                                for (Element link : links) {
                                    if (link.attr("abs:href").contains("https://member.neteller.com/member/signUp?")) {
                                        log.debug("readWebGmail :: Posting link found " + link.attr("abs:href"));
                                        updateLink(username, uPassword, id, link.attr("abs:href"), 1);
                                        found = true;
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                        if (found) {
                            break;
                        }
                    }
                }
            } catch (Throwable ex) {
                ex.printStackTrace();
            }

            try {
                if (!found) {
                    String html = message.getContent().toString();
                    org.jsoup.nodes.Document doc = Jsoup.parse(html);
                    Elements links = doc.select("a[href]");
                    for (Element link : links) {
                        if (link.attr("abs:href").contains("https://member.neteller.com/member/signUp?")) {
                            log.debug("readWebGmail :: Posting link found " + link.attr("abs:href"));
                            updateLink(username, uPassword, id, link.attr("abs:href"), 1);
                            break;
                        }
                    }
                }
            } catch (Throwable ex) {
                ex.printStackTrace();
            }

        } catch (Throwable ex) {
            log.debug("readAllMessages :: Error " + ex);
            ex.printStackTrace();
        }
    }

    private static void updateLink(String username, String password, String id, String link, int work) {
        try {
            StringBuilder request = new StringBuilder();
            request.append("<Request>");
            request.append("<username>").append(username).append("</username>");
            request.append("<password>").append(password).append("</password>");
            request.append("<id>").append(id).append("</id>");
            request.append("<link>").append(StringEscapeUtils.escapeXml(link)).append("</link>");
            request.append("<working>").append(work).append("</working>");
            request.append("</Request>");

            String req = URLEncoder.encode(request.toString(), "UTF-8");
            String uri = "http://" + IConstant.HOSTNAME + "/index.php?r=netellerAccount/updateLink";
            String param = "request=" + req;
            String response = HttpHelper.post(new URL(uri), param);

            Document document = DocumentHelper.parseText(response);
            String errorCode = document.valueOf("Response/errorcode");
            String msg = document.valueOf("Response/message");
            log.debug("updateWorking:: update " + msg);
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String s[]) {
        NetellerHotMailHelper.updateLink("mithun", "mithun", "105", "https://member.neteller.com/member/signUp?step=twostep&pei=245891&refId=4-12-79-69-161-117-226-143-196-96-142-229-153-199-158-177", 1);
    }
}
